package com.example.zzh.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.zzh.entity.*;
import com.example.zzh.service.*;
import com.example.zzh.utils.MyClass;
import com.example.zzh.utils.Result;
import com.example.zzh.utils.ResultGenerator;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.swagger2.mappers.ModelMapper;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 产品表 前端控制器
 * </p>
 *
 * @author zzh
 * @since 2023-08-13
 */
@RestController
@RequestMapping("/zzh-product")
public class ZzhProductController {

    @Autowired
    private ZzhProductService zzhProductService;

    @Autowired
    private ZzhProductUnitService zzhProductUnitService;

    @Autowired
    private ZzhProductAttributeService zzhProductAttributeService;

    @Autowired
    private ZzhProductCategoryService zzhProductCategoryService;

    @Autowired
    private ZzhProductPriceService zzhProductPriceService;

    @Autowired
    private ZzhProductStockService zzhProductStockService;

    @Autowired
    private ZzhDepotService zzhDepotService;

    @GetMapping("/option")
    @ApiOperation(value = "查询商品属性|计量单位|库存|类别信息", notes = "查询商品属性|计量单位|库存|类别信息")
    public Result option(){
        //商品计量单位信息
        List<ZzhProductUnit> zzhProductUnits=zzhProductUnitService.lambdaQuery().eq(ZzhProductUnit::getStatus,1).list();
        Map<Long,String> hashMapProductUnits=new HashMap<Long, String>();
        for (ZzhProductUnit i : zzhProductUnits) {
            hashMapProductUnits.put(i.getId(),i.getName());
        }

        //商品多属性信息
        List<ZzhProductAttribute> zzhProductAttributes=zzhProductAttributeService.lambdaQuery().eq(ZzhProductAttribute::getStatus,1).list();
        Map<Long,String> hashMapProductAttributes=new HashMap<Long, String>();
        for (ZzhProductAttribute i : zzhProductAttributes) {
            hashMapProductAttributes.put(i.getId(),i.getAttributeName());
        }

        //商品库存信息
        List<ZzhDepot> zzhDepots=zzhDepotService.lambdaQuery().eq(ZzhDepot::getStatus,1).list();
        Map<Long,String> hashMapDepots=new HashMap<Long, String>();
        ArrayList<ZzhProductStock> ZzhProductStocks=new ArrayList<ZzhProductStock>();
        ZzhProductStock zzhProductStock=null;
        for (ZzhDepot i : zzhDepots) {
            hashMapDepots.put(i.getId(),i.getName());
            zzhProductStock=new ZzhProductStock();
            zzhProductStock.setDepotId(i.getId());
            zzhProductStock.setCurrentNumber(BigDecimal.valueOf(0));
            zzhProductStock.setHighNumber(BigDecimal.valueOf(0));
            zzhProductStock.setLowNumber(BigDecimal.valueOf(0));
            ZzhProductStocks.add(zzhProductStock);
        }

        //商品类别信息
        List<ZzhProductCategory> list=zzhProductCategoryService.lambdaQuery().eq(ZzhProductCategory::getStatus,1).list();
        List<Map<String, Object>> treeData = new ArrayList<>();
        Map<Long, Map<String, Object>> map = new HashMap<>();
        for(int i=0;i<list.size();i++){
            ZzhProductCategory arrayList=list.get(i);
            Map<String,Object> node=new HashMap<>();
            node.put("id",arrayList.getId());
            node.put("label",arrayList.getName());
            // 将节点存储到map中，以便后续构建树形结构
            map.put(arrayList.getId(), node);
            if(arrayList.getParentId() != null){
                Map<String, Object> parent = map.get(arrayList.getParentId());
                if (parent != null) {
                    List<Map<String, Object>> children = (List<Map<String, Object>>) parent.get("children");
                    if (children == null) {
                        children = new ArrayList<>();
                        parent.put("children", children);
                    }
                    children.add(node);
                }
            } else {
                treeData.add(node); // 如果节点没有父节点，则将其作为根节点添加到treeData中
            }
        }
        Map<String,Object> data=new HashMap<>();
        data.put("hashMapProductUnits",hashMapProductUnits);
        data.put("hashMapProductAttributes",hashMapProductAttributes);
        data.put("hashMapDepots",hashMapDepots);
        data.put("listProductCategories",treeData);
        data.put("ZzhProductStocks",ZzhProductStocks);
        return ResultGenerator.genSuccessResult(data);
    }

    @PostMapping("/list")
    @ApiOperation(value = "查询所有商品详情分页", notes = "分页")
    public Result list(@RequestBody Map<String,Object> params){
        HashMap<String,Object> hashMap=new HashMap<>();
        if (StringUtils.isEmpty(params.get("page")) || StringUtils.isEmpty(params.get("limit"))) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        //分页标签
        Page<ZzhProduct> page=new Page<>();
        page.setCurrent((int) params.get("page"));
        page.setSize((int) params.get("limit"));
        if(!StringUtils.isEmpty(params.get("name"))){
            hashMap.put("name",params.get("name"));
        }
        if(!StringUtils.isEmpty(params.get("categoryId"))){
            hashMap.put("categoryId",params.get("categoryId"));
        }
        IPage r=null;
        //查询分页商品信息
        List<ZzhProductInfo> zzhProductInfoList=zzhProductService.selectProductList(page,hashMap);
        for(ZzhProductInfo zzhProductInfo : zzhProductInfoList){
            //设置默认商品总库存量
            BigDecimal productStockNum = BigDecimal.valueOf(0);
            List<ZzhProductStock> zzhProductStocks=zzhProductStockService.lambdaQuery().eq(ZzhProductStock::getMaterialId,zzhProductInfo.getId()).list();
            for(ZzhProductStock zzhProductStock : zzhProductStocks ){
                productStockNum=productStockNum.add(zzhProductStock.getCurrentNumber());
            }
            zzhProductInfo.setZzhProductStocks(zzhProductStocks);
            zzhProductInfo.setCurrentNumber(productStockNum);
        }
        System.out.println("zzhProductInfoList:"+zzhProductInfoList.toString());
        return ResultGenerator.genSuccessResult(zzhProductInfoList, (long) zzhProductService.lambdaQuery().eq(ZzhProduct::getStatus,1).list().size());
    }

    @PutMapping("/updateStatus")
    @ApiOperation(value = "修改商品详情状态", notes = "修改商品详情状态")
    public Result updateStatus(@RequestParam Long id){
        ZzhProduct zzhProduct=zzhProductService.getProductById(id);
        if(!Objects.isNull(zzhProduct)){
            if(zzhProduct.getStatus()==1){
                zzhProduct.setStatus(2);
            }else if(zzhProduct.getStatus()==2){
                zzhProduct.setStatus(1);
            }
            if(zzhProductService.updateById(zzhProduct)) {
                return ResultGenerator.genSuccessResult();
            }
            return ResultGenerator.genErrorResult(404,"更新不成功");
        }else {
            return ResultGenerator.genErrorResult(404,"更新不成功");
        }
    }

    @PostMapping("/add")
    @ApiOperation(value = "新增商品详情", notes = "新增商品详情")
    @Transactional
    public Result add(@RequestBody ZzhProductInfo zzhProductInfo){
        MyClass myClass=new MyClass();
        Boolean flag=false;
        ZzhProduct zzhProduct=new ZzhProduct();
        if(zzhProductInfo.getName()!=null && !"".equals(zzhProductInfo.getName())){
            //copy类
            myClass.mapBtoA(zzhProductInfo,zzhProduct);
            //保存商品表
            Long id=zzhProductService.saveProduct(zzhProduct);
            //判断新增是否成功
            if(id>0){
                flag=true;
            }
            if(zzhProduct.getId()!=null){
                flag=true;
            }
        }
        //判断是否输入商品条码
        if(zzhProductInfo.getBarCode()!=null && !"".equals(zzhProductInfo.getBarCode())){
            ZzhProductPrice zzhProductPrice=new ZzhProductPrice();
            myClass.mapBtoA(zzhProductInfo,zzhProductPrice);
            zzhProductPrice.setMaterialId(zzhProduct.getId());
            if(!zzhProductPriceService.save(zzhProductPrice)){
                flag=false;
            }
        }
        //判断商品库存列表是否为空
        if(zzhProductInfo.getZzhProductStocks()!=null){
            List<ZzhProductStock> zzhProductStocks=zzhProductInfo.getZzhProductStocks();
            for (ZzhProductStock zzhProductStock:zzhProductStocks) {
                zzhProductStock.setMaterialId(zzhProduct.getId());
                if(!zzhProductStockService.save(zzhProductStock)){
                    flag=false;
                }
            }
        }
        if(flag){
            return ResultGenerator.genSuccessResult();
        }else {
            return ResultGenerator.genErrorResult(404,"新增不成功");
        }
    }

    @PutMapping("/update")
    @ApiOperation(value = "修改商品详情", notes = "修改商品详情")
    public Result mod(@RequestBody ZzhProductInfo zzhProductInfo){
        System.out.println(zzhProductInfo.toString());
        MyClass myClass=new MyClass();
        ZzhProduct zzhProduct=new ZzhProduct();
        if(zzhProductInfo.getId()!=null){
            myClass.mapBtoA(zzhProductInfo,zzhProduct);
            if(!zzhProductService.updateById(zzhProduct)){
                return ResultGenerator.genErrorResult(404,"修改商品不成功");
            }
        }

        if(zzhProductInfo.getBarCode()!=null && !"".equals(zzhProductInfo.getBarCode())){
            ZzhProductPrice zzhProductPrice=new ZzhProductPrice();
            myClass.mapBtoA(zzhProductInfo,zzhProductPrice);
            zzhProductPrice.setMaterialId(zzhProduct.getId());
            LambdaQueryWrapper<ZzhProductPrice> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ZzhProductPrice::getMaterialId, zzhProduct.getId());
            ZzhProductPrice zzhProductPrice1=zzhProductPriceService.getOne(queryWrapper);
            zzhProductPrice.setId(zzhProductPrice1.getId());
            if(!zzhProductPriceService.updateById(zzhProductPrice)){
                return ResultGenerator.genErrorResult(404,"修改价格不成功");
            }
        }

        if(zzhProductInfo.getZzhProductStocks()!=null){
            List<ZzhProductStock> zzhProductStocks=zzhProductInfo.getZzhProductStocks();
            for (ZzhProductStock zzhProductStock:zzhProductStocks) {
                zzhProductStock.setMaterialId(zzhProduct.getId());
                if(!zzhProductStockService.saveOrUpdate(zzhProductStock)){
                    return ResultGenerator.genErrorResult(404,"修改库存不成功");
                }
            }
//            LambdaQueryWrapper<ZzhProductStock> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.eq(ZzhProductStock::getMaterialId, zzhProduct.getId());
//            ZzhProductStock zzhProductStock=zzhProductStockService.getOne(queryWrapper);
//            zzhProductStock.setCurrentNumber(zzhProductInfo.getCurrentNumber());
//            zzhProductStock.setHighNumber(zzhProductInfo.getHighNumber());
//            zzhProductStock.setLowNumber(zzhProductInfo.getLowNumber());
//            zzhProductStock.setDepotId(zzhProductInfo.getDepotId());
//            System.out.println(zzhProductStock.toString());
//            if(!zzhProductStockService.saveOrUpdate(zzhProductStock)){
//                return ResultGenerator.genErrorResult(404,"修改库存不成功");
//            }
        }
        return ResultGenerator.genSuccessResult();
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "删除商品详情", notes = "删除商品详情")
    public Result delete(@RequestParam Long id){
        ZzhProduct zzhProduct=zzhProductService.getProductById(id);
        List<ZzhProductPrice> zzhProductPrices=zzhProductPriceService.lambdaQuery().eq(ZzhProductPrice::getMaterialId,zzhProduct.getId()).list();
        if(!Objects.isNull(zzhProduct)){
            zzhProduct.setStatus(0);
            zzhProductPrices.get(0).setStatus(0);
            if(zzhProductService.updateById(zzhProduct)) {
                return ResultGenerator.genSuccessResult();
            }
            if(zzhProductPriceService.updateById(zzhProductPrices.get(0))) {
                return ResultGenerator.genSuccessResult();
            }
            return ResultGenerator.genErrorResult(404,"删除不成功");
        }else {
            return ResultGenerator.genErrorResult(404,"删除不成功");
        }
    }

}
